package com.apache.flow.timer;

import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.apache.common.DateUtil;
import com.apache.core.utils.SpringContextHolder;
import com.apache.flow.core.entity.FlowAutomaticProcessing;
import com.apache.flow.core.manager.FlowAutomaticProcessingManager;
import com.apache.tools.PostHttp;

public class AutoTaskTimer extends TimerTask {
	private static Logger logger = LoggerFactory.getLogger(AutoTaskTimer.class);
	private static transient boolean autoTaskExecFlag = true;
	private static AutoTaskTimer instance;

	public static AutoTaskTimer getInstance() {
		if (null == instance) {
			instance = new AutoTaskTimer();
		}
		return instance;
	}

	@Override
	public void run() {
		logger.info("自处理任务开始AutoTaskBegin^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" + DateUtil.getNowTime());
		if (autoTaskExecFlag) {
			autoTaskExecFlag = false;
			FlowAutomaticProcessingManager flowAutomaticProcessingManager = null;
			List<FlowAutomaticProcessing> list = null;
			try {
				flowAutomaticProcessingManager = SpringContextHolder.getBean("flowAutomaticProcessingManager");
				String currentTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
				logger.info("当前执行时间："+currentTime);
				list = flowAutomaticProcessingManager.getFlowAutoListByStatusAndTime("0", currentTime);
				logger.info("本次需要处理任务数："+list.size());
				
				for (FlowAutomaticProcessing flowAutomaticProcessing : list) {
					if (!flowAutomaticProcessingManager.checkAutoTaskIfValid(flowAutomaticProcessing.getProcessInsId())) {
						logger.info("------[NotValidAutoTask]:handleUrl=" + flowAutomaticProcessing.getHandleUrl());
						logger.info("该实例已经结束或者删除！无效的自处理任务！(This processInstance is ended or has been deleted!)");
						flowAutomaticProcessingManager.deleteAutomaticProcessingByProcessInsId(flowAutomaticProcessing
								.getProcessInsId());
						continue;
					}
					//远程调用自处理任务
					try {
						if (null != flowAutomaticProcessing.getHandleUrl()
								&& !"".equals(flowAutomaticProcessing.getHandleUrl())) {
							logger.info("------[DoAutoTask]:handleUrl=" + flowAutomaticProcessing.getHandleUrl());
							PostHttp.postHttpString(flowAutomaticProcessing.getHandleUrl(), null);
						}
					} catch (RuntimeException e1) {
						logger.error("定时器调用自处理任务发生运行时异常taskId=" + flowAutomaticProcessing.getTaskId()
								+ ",processInsId=" + flowAutomaticProcessing.getProcessInsId() + ",异常信息:"
								+ e1.getMessage());
					}
				}
			} catch (Exception e) {
				logger.error("定时器调用自处理任务时Exception:" + e.getMessage());
			} finally {
				autoTaskExecFlag = true;
			}
		}
		logger.info("自处理任务结束AutoTaskEnd^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" + DateUtil.getNowTime());
	}
}
